<!--
 * @Descripttion: (不良原因/Base_DefectItem)
 * @Author: (admin)
 * @Date: (2024-10-07)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item label="编号" prop="defectitemId">
        <el-input v-model="queryParams.defectitemId" placeholder="请输入编号"  style="width: 100px"/>
      </el-form-item>
      <el-form-item label="名称" prop="defectItemName">
        <el-input v-model="queryParams.defectItemName" placeholder="请输入不良原因名称" />
      </el-form-item>
      <el-form-item label="不良类型" prop="defectTypeId">
        <el-select v-model="queryParams.defectTypeId" placeholder="请选择不良类型">
            <el-option v-for="item in deftypeOptions" 
            :key="item.defectTypeId" :label="item.defectTypeName" :value="item.defectTypeId" :disabled="item.status == 1">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['basedefectitem:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown trigger="click" v-hasPermi="['basedefectitem:import']">
          <el-button type="primary" plain icon="Upload">
            {{ $t('btn.import') }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="upload">
                <importData
                  templateUrl="base/baseDefectitem/importTemplate"
                  importUrl="/base/baseDefectitem/importData"
                  @success="handleFileSuccess"></importData>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['basedefectitem:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange"
      >
      <el-table-column prop="defectitemId" label="编号" align="center" :show-overflow-tooltip="true" sortable v-if="columns.showColumn('defectitemId')" width="90px"/>
      <el-table-column prop="defectItemName" label="名称" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('defectItemName')"/>
      <el-table-column prop="defectTypeName" label="类型名称" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('defectTypeName')" width="100px"/>
      <el-table-column prop="create_by" label="创建用户" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('create_by')" width="90px"/>
      <el-table-column prop="create_time" label="创建时间" :show-overflow-tooltip="true"  v-if="columns.showColumn('create_bime')" width="160px"/>
      <el-table-column prop="update_by" label="更新用户" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('update_by')" width="90px"/>
      <el-table-column prop="update_time" label="更新时间" :show-overflow-tooltip="true"  v-if="columns.showColumn('update_time')" width="160px"/>
      <el-table-column prop="remark" label="备注" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('remark')" width="120px"/>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['basedefectitem:edit']" @click="handleUpdate(scope.row)"></el-button>
          <el-button type="danger" size="small" icon="delete" title="删除" v-hasPermi="['basedefectitem:delete']" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :lock-scroll="false" v-model="open" >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="编号" prop="defectitemId" style="width: 320px">
              <el-input v-model="form.defectitemId" placeholder="请输入不良原因编号" :disabled="showdefectItem"/>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="名称" prop="defectItemName">
              <el-input v-model="form.defectItemName" placeholder="请输入不良原因名称" />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="不良类型" prop="defectTypeId">
              <el-select v-model="form.defectTypeId" placeholder="请选择不良类型">
                <el-option label="全部" :value="-1" />  
                <el-option v-for="item in deftypeOptions" 
                  :key="item.defectTypeId" :label="item.defectTypeName" :value="item.defectTypeId" :disabled="item.status == 1">
                  </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="basedefectitem">
import { listbaseDefectitem,
 addbaseDefectitem, delbaseDefectitem, 
 updatebaseDefectitem,getbaseDefectitem, 
 } 
from '@/api/base/basedefectitem.js'
import importData from '@/components/ImportData'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const showdefectItem = ref(false)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: 'DefectitemId',
  sortType: 'asc',
  defectitemId: undefined,
  defectItemName: undefined,
  defectTypeId: undefined,
})
const columns = ref([
  { visible: true, align: 'center', type: '', prop: 'defectitemId', label: '不良原因编号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'defectItemName', label: '不良原因名称'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'defectTypeName', label: '不良类型'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'create_by', label: '创建用户'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'create_time', label: '创建时间'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'update_by', label: '更新用户'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'update_time', label: '更新时间'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'remark', label: 'Remark'  ,showOverflowTooltip: true  },
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
const deftypeOptions = ref([])

getbaseDefectitem("").then((res) => {
    deftypeOptions.value = res.data.deftypes
});

function getList(){
  loading.value = true
  listbaseDefectitem(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  });
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery(){
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

    if (column.prop == 'defectitemId') {
      sort = 'defectItemId'
    }
  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  form: {},
  rules: {
    defectitemId: [{ required: true, message: "不良原因编号不能为空", trigger: "blur" }],
    defectItemName: [{ required: true, message: "不良原因名称不能为空", trigger: "blur" }],
    defectTypeId: [{ required: true, message: "不良类型编号不能为空", trigger: "blur" }],
  },
  options: {
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel(){
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    defectitemId: null,
    defectItemName: null,
    defectTypeId: null,
    remark: null,
  };
  proxy.resetForm("formRef")
}

// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  title.value = '添加不良原因'
  opertype.value = 1
  showdefectItem.value = false
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.defectitemId || ids.value
  getbaseDefectitem(id).then((res) => {
    const code = res.code
    const data = res.data.defectitem
    form.value = {
      defectitemId: data.defectitemId,
      defectItemName: data.defectItemName,
      defectTypeId: data.defectTypeId,
      remark: data.remark,
    }
    if (code == 200) {
      open.value = true
      title.value = '修改不良原因'
      opertype.value = 2
      showdefectItem.value = true

    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {

      if (form.value.defectitemId != undefined && opertype.value === 2) {
        updatebaseDefectitem(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addbaseDefectitem(form.value).then((res) => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.defectitemId || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delbaseDefectitem(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}


// 导入数据成功处理
const handleFileSuccess = (response) => {
  const { item1, item2 } = response.data
  var error = ''
  item2.forEach((item) => {
    error += item.storageMessage + ','
  })
  proxy.$alert(item1 + '<p>' + error + '</p>', '导入结果', {
    dangerouslyUseHTMLString: true
  })
  getList()
}

// 导出按钮操作
function handleExport() {
  proxy
    .$confirm("是否确认导出不良原因数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      await proxy.downFile('/base/baseDefectitem/export', { ...queryParams })
    })
}

handleQuery()
</script>